package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.domain.LuckDrawSetting;
import com.lebang.domain.MemberAdStageRecord;
import com.lebang.domain.MemberAdvertisementRecord;
import com.lebang.domain.PointAdvertisementSetting;
import com.lebang.entity.LbbDict;
import com.lebang.example.LuckDrawSettingExample;
import com.lebang.example.PointAdvertisementSettingExample;
import com.lebang.mapper.*;
import com.lebang.model.AdModel;
import com.lebang.model.PointModel;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.lebang.controller.api.LuckDrawController.LUCKDRAW_BRAND_SET;
import static com.lebang.controller.api.LuckDrawController.LUCKDRAW_HASH_MEMBER;

/**
 * @Author: hwq
 * @Date: 2019/11/26 16:22
 * @Version 1.0
 */
@Service
public class LuckDrawService {
    @Autowired
    private RedisClient redisClient;
    private static final String JIN_BI_SETTING = "jin_bi_setting";
    @Autowired
    private LbbDictMapper lbbDictMapper;
    @Autowired
    private PointAdvertisementSettingMapper advertisementSettingMapper;
    @Autowired
    private MemberAdvertisementRecordMapper recordMapper;
    @Autowired
    private LuckDrawSettingMapper luckDrawSettingMapper;
    @Autowired
    private MemberAdStageRecordMapper memberAdStageRecordMapper;

    /**
     * 获取今日已抽奖次数
     *
     * @param memberId
     * @return
     */
    public int todayInit(String memberId) {

        int i = 0;
        boolean on = redisClient.hexists(getKey(), memberId);
        if (!on) {
            redisClient.hset(getKey(), memberId, "0");
            //过期时间修改注释
            //redisClient.expire(getKey(),86400);
        } else {
            String str = redisClient.hget(getKey(), memberId);
            i = Integer.parseInt(str);
        }
        return i;
    }

    /**
     * 抽奖次数+1
     *
     * @param memberId
     */
    public int addCount(String memberId) {
      return  redisClient.hincrBy(getKey(), memberId, 1).intValue();
    }

    public String getKey() {
        LocalDate date = LocalDate.now();
        return LUCKDRAW_HASH_MEMBER + date.format(DateTimeFormatter.ISO_DATE);
    }

    /**
     * 从缓存获取金币配置
     *
     * @return
     */
    public PointModel getPointSet() {
        PointModel pointModel = null;
        String str = redisClient.get(JIN_BI_SETTING);
        if (str == null) {
            LbbDict dict = lbbDictMapper.selectByKeyName("jinbipeizhi");
            if (dict != null) {
                pointModel = JSON.parseObject(dict.getKeyvalue(), PointModel.class);
                redisClient.set("jinbipeizhi", dict.getKeyvalue());
            } else {
                return null;
            }
        } else {
            pointModel = JSON.parseObject(str, PointModel.class);
        }
        return pointModel;
    }

        public List<PointAdvertisementSetting> selectAdByBrand(String brand, int k,int version) {
        PointAdvertisementSettingExample example = new PointAdvertisementSettingExample();
            example.createCriteria().andBrandNotLike("%"+brand+"%").andEnableEqualTo(1).andCategoryEqualTo(k).andVersionLessThanOrEqualTo(version);
        return advertisementSettingMapper.selectByExample(example);
    }

    public List<AdModel> selectAdModel(String brand, int k,int version) {
        List<AdModel> list = new ArrayList<>();
        String str = redisClient.hget(LUCKDRAW_BRAND_SET + k, brand+":"+version);
        if (str != null) {
            list = JSON.parseArray(str, AdModel.class);
        } else {
            List<PointAdvertisementSetting> list1 = this.selectAdByBrand(brand, k,version);
            for (Iterator<PointAdvertisementSetting> iterator = list1.iterator(); iterator.hasNext(); ) {
                PointAdvertisementSetting s = iterator.next();
                int size = s.getWeight();
                for (int i = 0; i < size; i++) {
                    list.add(new AdModel(s.getId()));
                }
            }
            if (list.size() > 0) {
                redisClient.hset(LUCKDRAW_BRAND_SET + k, brand+":"+version, JSON.toJSONString(list));
            }
        }
        return list;
    }

    public PointAdvertisementSetting selectAdById(Integer adId) {
        return advertisementSettingMapper.selectByPrimaryKey(adId);
    }

    public MemberAdvertisementRecord addPointRecord(String memberId, int point, int status) {
        MemberAdvertisementRecord record = new MemberAdvertisementRecord();
        record.setCreateTime(LocalDateTime.now());
        record.setModifyTime(LocalDateTime.now());
        record.setMoney(point);
        record.setStatus(status);
        record.setType(1);
        record.setParentId(0);
        record.setMemberId(memberId);
        record.setTitle("转盘抽奖");
        record.setIsDouble(0);
        recordMapper.insertSelective(record);
        return record;
    }

    /**
     * 获取设置第几个后，继续抽奖会出现广告
     *
     * @return
     */
    public int getPointAfterAd() {
        return Integer.parseInt(lbbDictMapper.selectByKeyName("chuxianguanggao").getKeyvalue());
    }

    /**
     * 设置第几个金币后出现不翻倍
     *
     * @return
     */
    public int getPointAfterDouble() {
        return Integer.parseInt(lbbDictMapper.selectByKeyName("jinbifanbei").getKeyvalue());
    }

    /**
     * 随机获取一个插屏广告或视频广告3
     *
     * @param brand
     * @param version
     * @return
     */
    public PointAdvertisementSetting selectVideoOrGift(String brand, int version) {
        List<AdModel> adModels = this.selectAdModel(brand, 3,version);
        adModels.addAll(this.selectAdModel(brand, 1,version));
        int random = RandomUtils.nextInt(0, adModels.size());
        AdModel click = adModels.get(random);
        return this.selectAdById(click.getAdId());
    }

    /**
     * 随机取一个礼物或插屏广告23
     *
     * @param brand
     * @return
     */
    public PointAdvertisementSetting selectGiftByBrand(String brand,int version) {
        List<AdModel> adModels = this.selectAdModel(brand, 2,version);
        adModels.addAll(this.selectAdModel(brand, 3,version));
        int random = RandomUtils.nextInt(0, adModels.size());
        AdModel click = adModels.get(random);
        return this.selectAdById(click.getAdId());
    }

    /**
     * 随机取一个视频广告1
     *
     * @param brand
     * @return
     */
    public PointAdvertisementSetting selectAdByBrand(String brand,int version) {
        List<AdModel> adModels = this.selectAdModel(brand, 1,version);
        int random = RandomUtils.nextInt(0, adModels.size());
        AdModel click = adModels.get(random);
        return this.selectAdById(click.getAdId());
    }

    /**
     * 随机取一个首页广告
     *
     * @param brand
     * @return
     */
    public PointAdvertisementSetting selectHomeByBrand(String brand,int version) {
        List<AdModel> adModels = this.selectAdModel(brand, 4,version);
        int random = RandomUtils.nextInt(0, adModels.size());
        AdModel click = adModels.get(random);
        return this.selectAdById(click.getAdId());
    }

    public MemberAdvertisementRecord selectRecordById(Integer id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    public int updateRecord(MemberAdvertisementRecord record) {
        record.setModifyTime(LocalDateTime.now());
        record.setIsDouble(1);
        MemberAdvertisementRecord record1 = new MemberAdvertisementRecord();
        record1.setType(2);
        record1.setMemberId(record.getMemberId());
        record1.setIsDouble(0);
        record1.setId(null);
        record1.setParentId(record.getId());
        record1.setMoney(record.getMoney() * 2);
        record1.setCreateTime(LocalDateTime.now());
        record1.setModifyTime(LocalDateTime.now());
        record1.setStatus(0);
        record1.setTitle("奖励翻倍");
        recordMapper.insertSelective(record1);
        return recordMapper.updateByPrimaryKeySelective(record);
    }

    public void clean() {
        redisClient.del("jinbipeizhi",LUCKDRAW_BRAND_SET + 1, LUCKDRAW_BRAND_SET + 2,LUCKDRAW_BRAND_SET + 3,LUCKDRAW_BRAND_SET + 4,LUCK_DRAW_LIST,LUCK_DRAW_LIST+":asc",JIN_BI_SETTING);
    }

    public void checkCount(String memberId, int i) {
        LocalDate date = LocalDate.now();
        LocalDateTime star = LocalDateTime.of(date, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
        LuckDrawSetting vo = this.getCountIn(i);
        if (vo == null) {
            return;
        }

        MemberAdStageRecord advertisementRecord = memberAdStageRecordMapper.selectByMemberIdAndCount(memberId, vo.getId(), star, end);
        if (advertisementRecord == null) {
            advertisementRecord = new MemberAdStageRecord();
            advertisementRecord.setCreateTime(LocalDateTime.now());
            advertisementRecord.setModifyTime(LocalDateTime.now());
            advertisementRecord.setMoney(vo.getMoney());
            advertisementRecord.setStatus(0);
            advertisementRecord.setMemberId(memberId);
            advertisementRecord.setDrawId(vo.getId());
            advertisementRecord.setCount(vo.getCount());
            memberAdStageRecordMapper.insertSelective(advertisementRecord);
        }
    }

    private static final String LUCK_DRAW_LIST = "luck_draw_list";

    private LuckDrawSetting getCountIn(int i) {
        String str = redisClient.get(LUCK_DRAW_LIST+":asc");
        List<LuckDrawSetting> luckDrawSettings;
        if (str != null) {
            luckDrawSettings = JSON.parseArray(str, LuckDrawSetting.class);
        } else {
            LuckDrawSettingExample example = new LuckDrawSettingExample();
            example.setOrderByClause("count desc");
            luckDrawSettings = luckDrawSettingMapper.selectByExample(example);
            redisClient.set(LUCK_DRAW_LIST+":asc",JSON.toJSONString(luckDrawSettings));
        }
        for (Iterator<LuckDrawSetting> iterator = luckDrawSettings.iterator(); iterator.hasNext(); ) {
            LuckDrawSetting next = iterator.next();
            if (i >= next.getCount()) {
                return next;
            }
        }
        return null;
    }

    /**
     * 获取今日待领取的阶段性奖励
     *
     * @param memberId
     * @return
     */
    public List<MemberAdStageRecord> selectStageRecordList(String memberId) {
        List<MemberAdStageRecord> adStageRecords=new ArrayList<>();
        LocalDate date = LocalDate.now();
        LocalDateTime star = LocalDateTime.of(date, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
        String str = redisClient.get(LUCK_DRAW_LIST);
        List<LuckDrawSetting> luckDrawSettings;
        if (str != null) {
            luckDrawSettings = JSON.parseArray(str, LuckDrawSetting.class);
        } else {
            LuckDrawSettingExample example = new LuckDrawSettingExample();
            example.setOrderByClause("count asc");
            example.createCriteria().andHasDeletedEqualTo(0);
            luckDrawSettings = luckDrawSettingMapper.selectByExample(example);
            redisClient.set(LUCK_DRAW_LIST,JSON.toJSONString(luckDrawSettings));
        }
        for (Iterator<LuckDrawSetting> iterator = luckDrawSettings.iterator(); iterator.hasNext(); ) {
            LuckDrawSetting next = iterator.next();
            MemberAdStageRecord vo=new MemberAdStageRecord();
            vo.setCount(next.getCount());
            vo.setMoney(next.getMoney());
            MemberAdStageRecord advertisementRecord = memberAdStageRecordMapper.selectByMemberIdAndCount(memberId, next.getId(), star, end);
            if(advertisementRecord==null){
                vo.setStatus(-1);
            }else {
                vo.setStatus(advertisementRecord.getStatus());
                vo.setId(advertisementRecord.getId());
            }
            adStageRecords.add(vo);
        }
        return adStageRecords;
    }

    public MemberAdStageRecord selectStageById(Integer id) {
        return memberAdStageRecordMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改待领取为已领取
     * @param record
     */
    public void updateStageRecord(MemberAdStageRecord record) {
        record.setModifyTime(LocalDateTime.now());
        record.setStatus(1);
        memberAdStageRecordMapper.updateByPrimaryKeySelective(record);
    }
}
